package com.example.maoguolin

import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import java.io.PrintWriter

class SecondActivity : AppCompatActivity() {
    private lateinit var listViewPrimes: ListView
    private lateinit var buttonClearHistory: Button // 引入按钮变量

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        listViewPrimes = findViewById(R.id.listViewPrimes)
        buttonClearHistory = findViewById(R.id.buttonClearHistory) // 初始化按钮

        // 加载素数
        loadPrimes()

        // 清除历史记录按钮添加点击事件
        buttonClearHistory.setOnClickListener {
            clearHistory() // 清除记录
        }
    }

    private fun loadPrimes() {
        val primes = mutableListOf<String>()
        val file = filesDir.resolve("primes.txt")
        if (file.exists()) {
            BufferedReader(InputStreamReader(file.inputStream())).use { reader ->
                reader.forEachLine { line -> primes.add(line) }
            }
        }
        val adapter = ArrayAdapter(this, R.layout.list_item, primes)
        listViewPrimes.adapter = adapter
    }

    private fun clearHistory() {
        val file = File(filesDir, "primes.txt")
        if (file.exists()) {
            file.delete() // 删除文件
        }
        (listViewPrimes.adapter as ArrayAdapter<*>).clear() // 清空列表
    }
}
